package com.zidian.study.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.EvaHotAdapter;
import com.zidian.study.bean.EvaluateCustomBean;
import com.zidian.study.bean.EvaluateTeacherBean;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ImageFactory;
import com.zidian.study.utils.ProgressBarBlackUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by GongCheng on 2016/11/30.
 */

public class EvaHotFragment extends BaseFragment {
    @Bind(R.id.hot_eva_list_rv)
    RecyclerView hotEvaListRv;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;
    @Bind(R.id.issue_edit)
    EditText issueEdit;

    private int startrow = 1;
    private boolean isLoading;
    private boolean isRefreshing;
    private List<EvaluateCustomBean.DataBean.ListBean> data;
    private EvaHotAdapter adapter;
    private Handler handler = new Handler();
    private EvaluateTeacherBean.DataBean teacherMessage = new EvaluateTeacherBean.DataBean();

    public static EvaHotFragment newInstance() {

        Bundle args = new Bundle();

        EvaHotFragment fragment = new EvaHotFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.send_evaluation)
    public void sendEvaluation() {
        evaluateCustom();
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        teacherMessage = (EvaluateTeacherBean.DataBean) getActivity().getIntent().getSerializableExtra("teacher");
        data = new ArrayList<>();
        adapter = new EvaHotAdapter(getActivity(), data);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        hotEvaListRv.setLayoutManager(layoutManager);
        hotEvaListRv.setAdapter(adapter);

        swipeRefreshWidget.setColorSchemeResources(R.color.green);
        swipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshWidget.setRefreshing(true);
                isRefreshing = true;
            }
        });
        swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        startrow = 1;
                        isRefreshing = true;
                        try {
                            getData(startrow + "");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, 1000);
            }
        });

        hotEvaListRv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        hotEvaListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = swipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                try {
                                    startrow++;
                                    getData(startrow + "");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 2000);
                    }
                }
            }
        });
        initData();
    }

    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    getData(startrow + "");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 1500);

    }

    /**
     * 获取测试数据
     */
    private void getData(String startrow) throws IOException {
        String loginUrl = Constant.URL_TEACHER + "EvaluateTeacher/CustomEvaluationTop";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("teacherId", teacherMessage.getTeacherId());
        map.put("operatorType", "学生");
        map.put("operatorId", GetUserInfo.getStudentId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(
                new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("E", e.toString());
                        if (swipeRefreshWidget != null) {
                            swipeRefreshWidget.setRefreshing(false);
                        }
                        isRefreshing = false;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (swipeRefreshWidget != null) {
                            swipeRefreshWidget.setRefreshing(false);
                        }

                        isRefreshing = false;
                        Log.e("T", response);
                        try {
                            JSONObject jsonObject = null;
                            jsonObject = new JSONObject(response);
                            int resultCode = jsonObject.getInt("code");

                            if (resultCode != 200) {
                                isLoading = true;
                                adapter.setHasMore(false);
                                adapter.notifyDataSetChanged();
                                adapter.notifyItemRemoved(adapter.getItemCount());
                                return;
                            } else {
                                Gson gson = new Gson();
                                EvaluateCustomBean model = gson.fromJson(response, EvaluateCustomBean.class);

                                data.addAll(model.getData().getList());
                                adapter.notifyDataSetChanged();
                                if (model.getData().getList().size() < 10) {
                                    isLoading = true;
                                    adapter.setHasMore(false);
                                } else {
                                    isLoading = false;
                                    adapter.setHasMore(true);
                                }


                            }

                        } catch (JSONException e) {

                        }

                    }
                }

        );
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_hot_eva;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void evaluateCustom() {

        //由于公用一个界面所以id就不再修改适应了

        if (issueEdit.getText().toString().length() == 0) {
            Snackbar.make(hotEvaListRv, "请输入回复内容！", Snackbar.LENGTH_SHORT).show();
            return;
        }

        String loginUrl = Constant.URL_TEACHER + "ToEvaluateOthers/CustomEvaluationColleagues";
        HashMap<String, String> map = new HashMap<>();
        map.put("role", "student");
        map.put("appraiserId", GetUserInfo.getStudentId(getActivity()));
        map.put("byEvaluatePersonId", teacherMessage.getTeacherId());
        map.put("evaluationContent", issueEdit.getText().toString().trim());
        map.put("token", GetUserInfo.getToken(getActivity()));
        ProgressBarBlackUtil.loadShow(getActivity());
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(hotEvaListRv, "评论失败！", Snackbar.LENGTH_SHORT).show();
                        return;
                    } else {
                        issueEdit.setText("");
                        Snackbar.make(hotEvaListRv, "评论成功！", Snackbar.LENGTH_SHORT).show();
                        data.clear();
                        adapter.clearDatas();
                        startrow = 1;
                        getData(startrow + "");
                        hotEvaListRv.scrollToPosition(data.size());
                    }

                } catch (JSONException e) {

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

    }
}
